package com.sqx.modules.course.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.utils.PageUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.app.utils.JwtUtils;
import com.sqx.modules.common.dao.CommonInfoDao;
import com.sqx.modules.common.entity.CommonInfo;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.course.dao.*;
import com.sqx.modules.course.entity.*;
import com.sqx.modules.course.entity.dto.BatchAddCourseDetailDto;
import com.sqx.modules.course.entity.dto.BatchAddCourseDetailsDto;
import com.sqx.modules.course.entity.dto.UpdateUrlDto;
import com.sqx.modules.course.service.CourseDetailsService;
import com.sqx.modules.course.util.FfmpegUtil;
import com.sqx.modules.course.util.ServerUtil;
import com.sqx.modules.file.utils.UploadVo;
import com.sqx.modules.orders.service.OrdersService;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import ws.schild.jave.info.MultimediaInfo;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.format.DateTimeFormatter;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.sqx.modules.course.util.FfmpegUtil.addAWriteWatermark;
import static com.sqx.modules.course.util.ServerUtil.getFileName;

@Service
public class CourseDetailsServiceImpl  extends ServiceImpl<CourseDetailsDao, CourseDetails> implements CourseDetailsService {

    @Autowired
    private CourseDao courseDao;
    @Autowired
    private CourseCollectDao courseCollectDao;
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private CourseUserDao courseUserDao;
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private UserService userService;
    @Autowired
    private AdsUnlockVideosDao adsUnlockVideosDao;
    @Autowired
    private CoursePursueDao coursePursueDao;

    @Autowired
    private CourseDetailsDao courseDetailsDao;
    @Autowired
    private CommonInfoDao commonInfoDao;

    @Override
    public Result insert(CourseDetails courseDetails) {
        if(courseDetails.getGoodNum()==null){
            courseDetails.setGoodNum(0);
        }
        baseMapper.insert(courseDetails);
        return Result.success();
    }

    @Override
    public Result updateCourseDetails(CourseDetails courseDetails) {
        CourseDetails courseDetails1 = baseMapper.selectById(courseDetails.getCourseDetailsId());
        if (!courseDetails1.getVideoUrl().equals(courseDetails.getVideoUrl())){
            MultimediaInfo videoInfo = FfmpegUtil.getVideoInfo(courseDetails.getVideoUrl(), 1);
            if (ObjectUtils.isNotEmpty(videoInfo)){
                int totalSeconds = (int) (videoInfo.getDuration() / 1000);
                int minutes = totalSeconds / 60;
                int seconds = totalSeconds % 60;
                DecimalFormat df = new DecimalFormat("00");
                courseDetails.setDuration(df.format(minutes) + ":" + df.format(seconds));
            }
        }
        baseMapper.updateById(courseDetails);
        return Result.success();
    }

    @Override
    public Result deleteCourseDetails(String ids) {
        String[] split = ids.split(",");
        baseMapper.deleteCourseDetails(split);
        return Result.success();
    }

    @Override
    public Result selectCourseDetailsById(Long id,String token){
        Course bean = courseDao.selectById(id);
        if(bean.getViewCounts()==null){
            bean.setViewCounts(1);
        }else{
            bean.setViewCounts(bean.getViewCounts()+1);
        }
        courseDao.updateById(bean);
        Long userId=null;
        if(StringUtils.isNotEmpty(token)){
            Claims claims = jwtUtils.getClaimByToken(token);
            if(claims != null && !jwtUtils.isTokenExpired(claims.getExpiration())){
                userId=Long.parseLong(claims.getSubject());
            }
        }

        //计算总集数
        LambdaQueryWrapper<CourseDetails> courseDetailsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        courseDetailsLambdaQueryWrapper.eq(CourseDetails::getCourseId,id);
        int count = baseMapper.selectCount(courseDetailsLambdaQueryWrapper);
        bean.setCourseDetailsCount(count);
        System.out.println("===============总集数"+count);
        //计算所有收费集数
        LambdaQueryWrapper<CourseDetails> detailsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        detailsLambdaQueryWrapper.eq(CourseDetails::getCourseId,id);
        detailsLambdaQueryWrapper.eq(CourseDetails::getIsPrice,1);
        int count1 = baseMapper.selectCount(detailsLambdaQueryWrapper);
        bean.setPriceNum(count1);
        System.out.println("===============收费集数"+count1);

        //是否追剧
        if(userId!=null){
            LambdaQueryWrapper<CoursePursue> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CoursePursue::getUserId,userId);
            queryWrapper.eq(CoursePursue::getCourseId,id);
            CoursePursue coursePursue = coursePursueDao.selectOne(queryWrapper);
            if (ObjectUtils.isNotEmpty(coursePursue))bean.setIsPursue(1);
            else bean.setIsPursue(0);
            //是否收藏
            LambdaQueryWrapper<CourseCollect> courseCollectLambdaQueryWrapper = new LambdaQueryWrapper<>();
            courseCollectLambdaQueryWrapper.eq(CourseCollect::getCourseId,bean.getCourseId());
            courseCollectLambdaQueryWrapper.eq(CourseCollect::getUserId,userId);
            List<CourseCollect> courseCollects = courseCollectDao.selectList(courseCollectLambdaQueryWrapper);
            bean.setIsCollect(ObjectUtils.isNotEmpty(courseCollects)?1:0);
        }else {
            bean.setIsPursue(0);
        }
        LambdaQueryWrapper<CoursePursue> pursueLambdaQueryWrapper = new LambdaQueryWrapper<>();
        pursueLambdaQueryWrapper.eq(CoursePursue::getCourseId,id);
        int count2 = coursePursueDao.selectCount(pursueLambdaQueryWrapper);
        bean.setPurseCount(count2);
        //查用户是否还需要付费和是否推荐
        if (userId != null) {

            UserEntity userEntity = userService.selectUserById(userId);
            System.out.println("============="+userEntity);
            //查询用户是否购买了整集
            CourseUser courseUser = courseUserDao.selectCourseUser(id, userId);
            if (courseUser != null || (userEntity.getMember()!=null && userEntity.getMember()==2)) {
                bean.setListsDetail(baseMapper.findByCourseId(id,userId));//返回整部剧
                System.out.println("购买了整部剧");
                bean.setPriceNum(0);
            }else{
                // if(is_price!=1,c.video_url,'') 的作用是：
                //如果 is_price 不等于 1，则返回 c.video_url 的值。
                //如果 is_price 等于 1，则返回一个空字符串 ''。
                //根据短剧id查出当前所有剧集，如果付费视频地址为‘’，不付费返回视频地址
                bean.setListsDetail(baseMapper.findByCourseIdNotUrl(id,userId));
                //查询用户是否单独购买了单集
                List<CourseUser> courseUsers = courseUserDao.selectCourseUserList(id, userId);
                int priceTotal = 0;//付费集数
                if(courseUsers.size()>0){
                    for (CourseUser courseUser1:courseUsers){
                        for (CourseDetails courseDetails:bean.getListsDetail()) {
                            //查询用户是否观看广告
                            LambdaUpdateWrapper<AdsUnlockVideos> adsUnlockVideosLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                            adsUnlockVideosLambdaUpdateWrapper.eq(AdsUnlockVideos::getUserId,userId);
                            adsUnlockVideosLambdaUpdateWrapper.eq(AdsUnlockVideos::getCourseDetailsId,courseDetails.getCourseDetailsId());
                            adsUnlockVideosLambdaUpdateWrapper.eq(AdsUnlockVideos::getUnlockStatus,1);
                            AdsUnlockVideos adsUnlockVideos = adsUnlockVideosDao.selectOne(adsUnlockVideosLambdaUpdateWrapper);
                            //广告解锁或购买单集返回视频链接
                            if(ObjectUtils.isNotEmpty(adsUnlockVideos)||courseUser1.getCourseDetailsId().equals(courseDetails.getCourseDetailsId())){
                                CourseDetails courseDetails1 = baseMapper.selectById(courseDetails.getCourseDetailsId());
                                courseDetails.setVideoUrl(courseDetails1.getVideoUrl());
                                courseDetails.setIsUnlockVideos(1);
                                priceTotal = priceTotal+1;
                                System.out.println("用户购买了单集,剧集id"+courseDetails.getCourseDetailsId());
                            }
                            //收藏数量
                            LambdaQueryWrapper<CourseCollect> courseCollectLambdaQueryWrapper = new LambdaQueryWrapper<>();
                            courseCollectLambdaQueryWrapper.eq(CourseCollect::getCourseDetailsId,courseDetails.getCourseDetailsId());
                            courseCollectLambdaQueryWrapper.eq(CourseCollect::getCourseId,courseDetails.getCourseId());
                            courseCollectLambdaQueryWrapper.eq(CourseCollect::getUserId,userId);
                            courseCollectLambdaQueryWrapper.eq(CourseCollect::getClassify,1);
                            courseDetails.setCollectNum(courseCollectDao.selectCount(courseCollectLambdaQueryWrapper));
                            //点赞数量
                        }
                    }
                }
                if(count1>=priceTotal){
                    bean.setPriceNum(count1-priceTotal);//付费集数
                    System.out.println("该短剧付费总集数==============="+count1);
                    System.out.println("单集购买集数==============="+priceTotal);
                }else {
                    System.out.println("购买单集大于总集数");
                    bean.setPriceNum(0);//付费集数
                }
            }

            /*for (CourseDetails courseDetails:bean.getListsDetail()){
                courseDetails.setIsCollect(courseCollectDao.selectCount(new QueryWrapper<CourseCollect>()
                        .eq("user_id", userId).eq("course_details_id", courseDetails.getCourseDetailsId()).eq("classify",1)));
                courseDetails.setIsGood(courseCollectDao.selectCount(new QueryWrapper<CourseCollect>()
                        .eq("user_id", userId).eq("course_details_id", courseDetails.getCourseDetailsId()).eq("classify",2)));
            }*/

        } else {
            bean.setListsDetail(baseMapper.findByCourseIdNotUrl(id,null));
        }
        return Result.success().put("data",bean);
    }

    @Override
    public Result selectCourseDetailsList(Integer page,Integer limit,String token){
        Long userId=null;
        if(StringUtils.isNotEmpty(token)){
            Claims claims = jwtUtils.getClaimByToken(token);
            if(claims != null && !jwtUtils.isTokenExpired(claims.getExpiration())){
                userId=Long.parseLong(claims.getSubject());
            }
        }
        //查询CourseDetails中所有推荐的短剧
        IPage<CourseDetails> courseDetailsIPage = baseMapper.selectCourseDetailsList(new Page<>(page, limit));

        if (userId != null) {
            List<CourseDetails> records = courseDetailsIPage.getRecords();
            for (CourseDetails courseDetails:records){
                //用户是否追剧：0否1是
                Integer isPursue = coursePursueDao.selectCount(new LambdaQueryWrapper<CoursePursue>()
                        .eq(CoursePursue::getUserId, userId).eq(CoursePursue::getCourseId, courseDetails.getCourseId()));
                courseDetails.setIsPursue(isPursue);
                Integer purseCount = coursePursueDao.selectCount(new LambdaQueryWrapper<CoursePursue>()
                        .eq(CoursePursue::getCourseId, courseDetails.getCourseId()));
                courseDetails.setPurseCount(purseCount);
                //用户是否收藏：0否1是
                courseDetails.setIsCollect(courseCollectDao.selectCount(new QueryWrapper<CourseCollect>()
                        .eq("user_id", userId)
                        .eq("course_details_id", courseDetails.getCourseDetailsId())
                        .eq("classify",1)));
                //用户是否点赞：0否1是
                courseDetails.setIsGood(courseCollectDao.selectCount(new QueryWrapper<CourseCollect>()
                        .eq("user_id", userId)
                        .eq("course_details_id", courseDetails.getCourseDetailsId())
                        .eq("classify",2)));
                Course course = courseDao.selectById(courseDetails.getCourseId());
                course.setPurseCount(purseCount);
                course.setIsPursue(isPursue);
                courseDetails.setCourse(course);
                if (ObjectUtils.isNotEmpty(courseDetails.getCourse().getCourseLabel())){
                    String[] split = courseDetails.getCourse().getCourseLabel().split(",");
                    courseDetails.getCourse().setLabelList(split);
                    courseDetails.setLabelList(split);
                }
                courseDetails.setTitle(courseDetails.getCourse().getTitle());
                courseDetails.setCourseDetailsCount(baseMapper.selectCount(new QueryWrapper<CourseDetails>().eq("course_id",courseDetails.getCourseId())));
            }
        }else {
            for (CourseDetails record : courseDetailsIPage.getRecords()) {
                record.setCourse(courseDao.selectById(record.getCourseId()));
                if (ObjectUtils.isNotEmpty(record.getCourse().getCourseLabel())){
                    String[] split = record.getCourse().getCourseLabel().split(",");
                    record.getCourse().setLabelList(split);
                    record.setLabelList(split);
                }
                //用户是否追剧：0否1是
                record.setIsPursue(0);
                record.setPurseCount(coursePursueDao.selectCount(new LambdaQueryWrapper<CoursePursue>()
                        .eq(CoursePursue::getCourseId,record.getCourseId())));
                record.setTitle(record.getCourse().getTitle());
                record.setCourseDetailsCount(baseMapper.selectCount(new QueryWrapper<CourseDetails>().eq("course_id",record.getCourseId())));
            }
        }
        return Result.success().put("data",new PageUtils(courseDetailsIPage));
    }

    /**
     * 删除在追的剧
     * @param ids 剧id
     * @param userId 用户id
     * @return
     */
    @Override
    public void deleteCourseDetailsById(Long[] ids, Long userId) {
        LambdaUpdateWrapper<CourseCollect> courseCollectLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        courseCollectLambdaUpdateWrapper.eq(CourseCollect::getUserId,userId).in(CourseCollect::getCourseId,ids);
        courseCollectLambdaUpdateWrapper.eq(CourseCollect::getClassify,3);
        courseCollectDao.delete(courseCollectLambdaUpdateWrapper);
    }


    @Override
    public void aa() {
        LambdaQueryWrapper<CourseDetails> courseDetailsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        courseDetailsLambdaQueryWrapper.ge(CourseDetails::getCourseDetailsId,267);
        List<CourseDetails> courseDetails = courseDetailsDao.selectList(courseDetailsLambdaQueryWrapper);
        for (CourseDetails record : courseDetails) {
            MultimediaInfo videoInfo = null;
            try {
                videoInfo = FfmpegUtil.getVideoInfo(record.getVideoUrl(), 1);
            }catch (Exception e){
                e.printStackTrace();
                System.out.println("============>"+e.getMessage());
            }
            System.out.println("============>"+videoInfo.getDuration());
            int totalSeconds = (int) (videoInfo.getDuration() / 1000);
            int minutes = totalSeconds / 60;
            int seconds = totalSeconds % 60;
            DecimalFormat df = new DecimalFormat("00");
            record.setDuration(df.format(minutes) + ":" + df.format(seconds));
            courseDetailsDao.updateById(record);
        }
    }

    @Autowired
    private CommonInfoService commonRepository;
    //批量添加水印
    @Override
    public void batchAddCourseDetail(BatchAddCourseDetailDto batchAddCourseDetailDto) throws Exception{
        if (ObjectUtils.isNotEmpty(batchAddCourseDetailDto.getUploadVos())){
            for (UploadVo uploadVo : batchAddCourseDetailDto.getUploadVos()) {
                CourseDetails courseDetails = BeanUtil.toBean(batchAddCourseDetailDto, CourseDetails.class);
                courseDetails.setCourseId(batchAddCourseDetailDto.getCourseId().longValue());
                courseDetails.setVideoUrl(uploadVo.getFileUrl());
                if (ObjectUtils.isNotEmpty(uploadVo.getOriginalFilename())){
                    //去掉文件后缀
                    String str = uploadVo.getOriginalFilename();
                    int lastDotIndex = str.lastIndexOf('.');
                    if (lastDotIndex!= -1) {
                        str = str.substring(0, lastDotIndex);
                    }
                    courseDetails.setCourseDetailsName(str);
                }
                if (ObjectUtils.isNotEmpty(batchAddCourseDetailDto.getPrice())||batchAddCourseDetailDto.getPrice().compareTo(new BigDecimal(0))==0){
                    courseDetails.setPrice(BigDecimal.ZERO);
                    courseDetails.setIsPrice(2);
                }else {
                    courseDetails.setIsPrice(1);
                    courseDetails.setPrice(batchAddCourseDetailDto.getPrice());
                }
                courseDetails.setTitleImg(batchAddCourseDetailDto.getTitleImage());
                MultimediaInfo videoInfo = null;
                try {
                    videoInfo = FfmpegUtil.getVideoInfo(uploadVo.getFileUrl(), 1);
                }catch (Exception e){
                    e.printStackTrace();
                }
                if (ObjectUtils.isNotEmpty(videoInfo)){
                    int totalSeconds = (int) (videoInfo.getDuration() / 1000);
                    int minutes = totalSeconds / 60;
                    int seconds = totalSeconds % 60;
                    DecimalFormat df = new DecimalFormat("00");
                    courseDetails.setDuration(df.format(minutes) + ":" + df.format(seconds));
                }
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                courseDetails.setCreateTime(simpleDateFormat.format(new Date()));
                courseDetailsDao.insert(courseDetails);
            }
        }
    }

    @Override
    public Result uploadExcel(MultipartFile file) {
        List<List<String>> data = new ArrayList<>();
        try {
            Workbook workbook = new XSSFWorkbook(file.getInputStream());
            Sheet sheet = workbook.getSheetAt(0);
            Iterator<Row> rowIterator = sheet.iterator();
            while (rowIterator.hasNext()) {
                Row row = rowIterator.next();
                Iterator<Cell> cellIterator = row.cellIterator();
                List<String> rowData = new ArrayList<>();
                while (cellIterator.hasNext()) {
                    Cell cell = cellIterator.next();
                    switch (cell.getCellType()) {
                        case STRING:
                            rowData.add(cell.getStringCellValue());
                            break;
                        case NUMERIC:
                            rowData.add(String.valueOf(cell.getNumericCellValue()));
                            break;
                        case BOOLEAN:
                            rowData.add(String.valueOf(cell.getBooleanCellValue()));
                            break;
                        default:
                            rowData.add("");
                    }
                }
                data.add(rowData);
            }
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (ObjectUtils.isEmpty(data) || data.size() == 1) {
            Result.error("导入数据为空");
        }
        List<String> strings = data.get(0);
        return Result.success();
    }
    @Autowired
    private CourseDetailsService courseDetailsService;
    @Override
    public Result batchAddCourseDetails(BatchAddCourseDetailsDto batchAddCourseDetailsDto) {
        //获取剧集名
//        List<String> fileName = null;
//        try {
//            fileName = getFileName(batchAddCourseDetailsDto.getFileName());
//        }catch (Exception e){
//            e.printStackTrace();
//            return Result.error(200,"短剧名输入错误");
//        }
        List<String> fileName = batchAddCourseDetailsDto.getFileNames();
        Course course = courseDao.selectById(batchAddCourseDetailsDto.getCourseId());
        LambdaQueryWrapper<CourseDetails> courseDetailsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        courseDetailsLambdaQueryWrapper.eq(CourseDetails::getCourseId,course.getCourseId());
        List<CourseDetails> details = courseDetailsDao.selectList(courseDetailsLambdaQueryWrapper);
        HashMap<String,Object> map = new HashMap<>();
        if (ObjectUtils.isNotEmpty(details)){
            for (CourseDetails detail : details)
                map.put(detail.getCourseDetailsName(),detail);
        }
        int total = 0;
        ArrayList<CourseDetails> arrayList = new ArrayList<>();
        if (ObjectUtils.isNotEmpty(fileName)){
            long start = System.currentTimeMillis();
            for (String name : fileName) {
                CourseDetails courseDetails = new CourseDetails();
                courseDetails.setCourseId(batchAddCourseDetailsDto.getCourseId().longValue());
                //去掉文件后缀
                int lastDotIndex = name.lastIndexOf('.');
                if (lastDotIndex!= -1) {
                    String str = name.substring(0, lastDotIndex);
                    if (map.containsKey(str)){
                        System.out.println("第"+str+"集已存在");
                        continue;
                    }
                    String substring = name.substring(0, 1);
                    if (substring.equals("0")){
                        str = name.substring(1, lastDotIndex);
                    }
                    courseDetails.setCourseDetailsName("第"+str+"集 | "+batchAddCourseDetailsDto.getFileName());
                    if (ObjectUtils.isNotEmpty(batchAddCourseDetailsDto.getSort())){
                        courseDetails.setSort(batchAddCourseDetailsDto.getSort());
                    }else {
                        courseDetails.setSort(Integer.valueOf(str));
                    }
                }
                //拼接视频url
                String writePath = commonInfoDao.findOne(257).getValue();
                String domainName = commonInfoDao.findOne(256).getValue();
                String url = domainName + writePath + batchAddCourseDetailsDto.getFileName() + "/" + name;
                courseDetails.setVideoUrl(url);
                if (ObjectUtils.isNotEmpty(course.getTitleImg()))courseDetails.setTitleImg(course.getTitleImg());
                if (ObjectUtils.isNotEmpty(batchAddCourseDetailsDto.getContent()))courseDetails.setContent(batchAddCourseDetailsDto.getContent());
                if (ObjectUtils.isNotEmpty(batchAddCourseDetailsDto.getGoodNum()))courseDetails.setGoodNum(batchAddCourseDetailsDto.getGoodNum());
                if (ObjectUtils.isEmpty(batchAddCourseDetailsDto.getPrice())||batchAddCourseDetailsDto.getPrice().compareTo(BigDecimal.ZERO)==0){
                    courseDetails.setPrice(BigDecimal.ZERO);
                    courseDetails.setIsPrice(2);
                }else {
                    courseDetails.setPrice(batchAddCourseDetailsDto.getPrice());
                    courseDetails.setIsPrice(1);
                }

                long ll = System.currentTimeMillis();
                MultimediaInfo videoInfo = null;
                try {
                    videoInfo = FfmpegUtil.getVideoInfo(url, 1);
                }catch (Exception e){
                    e.printStackTrace();
                }
                if (ObjectUtils.isNotEmpty(videoInfo)){
                    int totalSeconds = (int) (videoInfo.getDuration() / 1000);
                    int minutes = totalSeconds / 60;
                    int seconds = totalSeconds % 60;
                    DecimalFormat df = new DecimalFormat("00");
                    courseDetails.setDuration(df.format(minutes) + ":" + df.format(seconds));
                }
                long bb = System.currentTimeMillis();
                System.out.println("获取视频时长耗时：" + (bb - ll) + "毫秒");
                String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                courseDetails.setCreateTime(format);
                arrayList.add(courseDetails);
                total = total + 1;
                System.out.println("域名======拼接链接："+url);

            }
            long end = System.currentTimeMillis();
            System.out.println("获取视频时长总耗时：" + (end - start) + "毫秒");
            courseDetailsService.saveBatch(arrayList);
        }
        return Result.success("添加成功");
    }


    @Override
    public Result getFileResourceName(String fileName) {
        List<String> names = null;
        List<String> toNames = new ArrayList<>();
        int total = 0;
        try {
            LambdaQueryWrapper<CommonInfo> commonInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            commonInfoLambdaQueryWrapper.ge(CommonInfo::getId,251);
            commonInfoLambdaQueryWrapper.le(CommonInfo::getId,257);
            List<CommonInfo> commonInfos = commonInfoDao.selectList(commonInfoLambdaQueryWrapper);
            HashMap<Long, CommonInfo> map = new HashMap<>();
            for (CommonInfo info : commonInfos) {
                map.put(info.getId(),info);
            }
            names = getFileName(fileName,map);
            for (String name : names) {
                if (name.endsWith(".mp4") || name.endsWith(".avi") || name.endsWith(".mkv") || name.endsWith(".mov") || name.endsWith(".wmv") || name.endsWith(".flv") || name.endsWith(".webm") || name.endsWith(".mpeg") || name.endsWith(".mpg") || name.endsWith(".m4v") || name.endsWith(".3gp")){
                    toNames.add(name);
                    total = total + 1;
                }
            }
            return Result.success().put("fileNames",toNames).put("successfulCount",total).put("loseCount",0);
        }catch (Exception e){
            e.printStackTrace();
            return Result.error(501,"短剧名输入错误或读取文件路径错误");
        }
    }

    @Override
    public Result getFileImgName(String fileName) {
        List<String> names = null;
        List<String> imgNames = new ArrayList<>();
        int total = 0;
        try {
            LambdaQueryWrapper<CommonInfo> commonInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            commonInfoLambdaQueryWrapper.ge(CommonInfo::getId,251);
            commonInfoLambdaQueryWrapper.le(CommonInfo::getId,257);
            List<CommonInfo> commonInfos = commonInfoDao.selectList(commonInfoLambdaQueryWrapper);
            HashMap<Long, CommonInfo> map = new HashMap<>();
            for (CommonInfo info : commonInfos) {
                map.put(info.getId(),info);
            }
            names = getFileName(fileName,map);
            for (String name : names) {
                if (name.endsWith(".jpg") || name.endsWith(".jpeg") || name.endsWith(".png") || name.endsWith(".gif") || name.endsWith(".bmp")) {
                    imgNames.add(name);
                    total = total + 1;
                }
            }
            return Result.success().put("imgNames",imgNames).put("successfulCount",total).put("loseCount",0);
        }catch (Exception e){
            e.printStackTrace();
            return Result.error(501,"短剧名输入错误或读取文件路径错误");
        }
    }

    @Override
    public Result detailsSort() {
        LambdaQueryWrapper<CourseDetails> courseDetailsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        courseDetailsLambdaQueryWrapper.ge(CourseDetails::getCourseDetailsId,632);
        List<CourseDetails> courseDetails = courseDetailsDao.selectList(courseDetailsLambdaQueryWrapper);
        for (CourseDetails courseDetail : courseDetails) {
            String name = courseDetail.getCourseDetailsName();
            int startIndex = name.indexOf("第") + 1;
            int endIndex = name.indexOf("集");
            if (startIndex > 0 && endIndex > startIndex) {
                String extractedString = name.substring(startIndex, endIndex);
                courseDetail.setSort(Integer.parseInt(extractedString));
            } else {
                System.out.println("无法提取有效内容======="+name);
            }
            courseDetailsDao.updateById(courseDetail);
        }

        return null;
    }

    /**
     * 修改剧集视频链接
     * @return
     */
    @Override
    public Result updateUrl(UpdateUrlDto updateUrlDto) {
        List<CourseDetails> courseDetails = courseDetailsDao.selectList(null);
        for (CourseDetails courseDetail : courseDetails) {
            String videoUrl = courseDetail.getVideoUrl();
            String replace = videoUrl.replace(updateUrlDto.getStr(), updateUrlDto.getReplaceStr());
            courseDetail.setVideoUrl(replace);
            courseDetailsDao.updateById(courseDetail);
        }
        return Result.success();
    }

    @Override
    public Result updateTitleImg() {
        List<Course> courses = courseDao.selectList(null);
        for (Course course : courses) {
            course.setTitleImg("https://u1.7wcloud.com/img/jz/"+course.getTitle()+".jpg");
            courseDao.updateById(course);
        }
        return Result.success();
    }

    @Override
    public Result updateDetailImg() {
        LambdaQueryWrapper<CourseDetails> courseDetailsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        courseDetailsLambdaQueryWrapper.ge(CourseDetails::getCourseDetailsId,574);
        List<CourseDetails> courseDetails = courseDetailsDao.selectList(courseDetailsLambdaQueryWrapper);
        for (CourseDetails courseDetail : courseDetails) {
            courseDetail.setTitleImg(courseDao.selectById(courseDetail.getCourseId()).getTitleImg());
            courseDetailsDao.updateById(courseDetail);
        }
        return Result.success();
    }




}
